﻿

CREATE PROCEDURE [dbo].[exbug_ExecutieCheltuieliPacientiArtAl]
	-- Add the parameters for the stored procedure here
	@CodUnitate smallint, 
	@Data datetime,
	@IDCasaAsigSanatate varchar(50),
	@IDJurnal int
AS
BEGIN
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	INSERT INTO [ExecutieCheltuieliPacienti]
           ([IDCasaAsigSanatate]
           ,[Data]
           ,[Internati]
           ,[ZileSpitalizare]
           ,[CodUnitate]
           ,[IDJurnal]
           ,[IDDepartament])
     SELECT @IDCasaAsigSanatate,@Data,0,0,@CodUnitate,@IDJurnal,IDDepartament  FROM Departamente a WHERE [CodUnitate]=@CodUnitate and a.ExecutieCheltuieli=1 
     AND NOT EXISTS(SELECT * FROM [ExecutieCheltuieliPacienti] e WHERE a.IDDepartament= e.IDDepartament AND a.CodUnitate=e.CodUnitate and MONTH(e.Data)=Month(@Data)and YEAR(e.Data)=YEAR(@Data)  and e.[IDCasaAsigSanatate] = @IDCasaAsigSanatate
     AND e.IDJurnal = @IDJurnal)
     
     DELETE FROM [ExecutieCheltuieliPacienti] WHERE 
     NOT EXISTS(SELECT * FROM Departamente a  WHERE [ExecutieCheltuieliPacienti].IDDepartament= a.IDDepartament AND a.CodUnitate=@CodUnitate AND a.ExecutieCheltuieli=1)
      and MONTH([ExecutieCheltuieliPacienti].Data)=Month(@Data) and YEAR([ExecutieCheltuieliPacienti].Data)=YEAR(@Data) and [ExecutieCheltuieliPacienti].[IDCasaAsigSanatate] = @IDCasaAsigSanatate
     AND [ExecutieCheltuieliPacienti].IDJurnal = @IDJurnal AND [ExecutieCheltuieliPacienti].CodUnitate=@CodUnitate

END